<?php
namespace app\taobao\controller;

use Curl\Curl;
use taobao\top\request\ItemImgUploadRequest;
use taobao\top\request\ItemUpdateRequest;
use taobao\top\TopClient;
use taobao\top\request\ItemAddRequest;
use taobao\top\request\ItempropsGetRequest;
use taobao\top\request\ItemcatsGetRequest;
use taobao\top\request\ItempropvaluesGetRequest;
use taobao\top\request\ItemPropimgUploadRequest;
use taobao\top\request\PictureUploadRequest;
use think\Request;
use think\Db;
use app\common\controller\Base;
use app\common\service\User as UserService;
use \Redis;


class Api extends Base
{
    protected $appKey = '';

    protected $appSecret = '';

    protected $topClient = null;

    protected $resp = null;

    protected $loginSession = '';

    protected $itemUrl = 'https://item.taobao.com/item.htm?spm=a1z10.1-c.w5003-15459902196.4.213f10e6twNyUx&id=542051820668&scene=taobao_shop';

    protected $rootPath = 'E:\money\caiji\python\dev';

    protected $user = null;

    public function __construct()
    {
        $userService = new UserService();
        $this->user = $userService->getCurrentUser();
        if(!$this->user->taobaosession){
            $this->error("请先登录淘宝",'/admin/index/main');
        }
        $this->loginSession = $this->user->taobaosession;

        if (!defined("TOP_SDK_WORK_DIR"))
        {
            define("TOP_SDK_WORK_DIR", EXTEND_PATH."taobao\\log\\");
        }

        /**
         * 是否处于开发模式
         * 在你自己电脑上开发程序的时候千万不要设为false，以免缓存造成你的代码修改了不生效
         * 部署到生产环境正式运营后，如果性能压力大，可以把此常量设定为false，能提高运行速度（对应的代价就是你下次升级程序时要清一下缓存）
         */
        if (!defined("TOP_SDK_DEV_MODE"))
        {
            define("TOP_SDK_DEV_MODE", true);
        }

        $taobaoConfig = Config("taobao");
        $this->appKey = $taobaoConfig['appKey'];
        $this->appSecret = $taobaoConfig['appSecret'];

        $this->topClient = new TopClient();
        $this->topClient->appkey = $this->appKey;
        $this->topClient->secretKey = $this->appSecret;

    }



    private function getItemIdFromQueue(){
        $path = $this->rootPath.DS.'queue'.DS.'finished_tasks.txt';
        $content = file_get_contents($path);
        $content = json_decode($content,true);
        $first = array_shift($content);
        $content = json_encode($content);
        file_put_contents($path,$content);
        return $first;
    }

    private function getItemBasicInfo($itemId){
        $path= $this->rootPath.DS.'csv'.DS.$itemId.'.txt';
        $content = file_get_contents($path);

        $res = preg_match_all('/"([^"]*)"=>"([^"]*)"/',$content,$match);
        if($res){
            $basicInfo = array_combine($match[1],$match[2]);
        }else{
            return [];
        }

        return $basicInfo;
    }

    private function getDescImg($itemId){
        $path = $this->rootPath.DS.'csv'.DS.'taobaoPack'.$itemId.DS.'media';
        $dir = opendir($path);
        $imageList = [];
        while($fileName = readdir($dir)){
            if($fileName !== '.' && $fileName !== '..'){
                array_push($imageList,$path.DS.$fileName);
            }
        }
        return $imageList;
    }

    private function getMajor($itemId){
        $path = $this->rootPath.DS.'csv'.DS.'taobaoPack'.$itemId;
        $dir = opendir($path);
        $imageList = [];
        while($fileName = readdir($dir)){
            if(strpos($fileName,'zhutu') !== false){
                array_push($imageList,$path.DS.$fileName);
            }
        }
        return $imageList;
    }

    //获取属性图片
    private function getPropsImage($itemId,$colorInfo){
        $path = $this->rootPath.DS.'csv'.DS.'taobaoPack'.$itemId;

        foreach($colorInfo as $key => $val ){
            $colorInfo[$key]['path'] = $path.DS.$val[0].'.jpg';
        }

        return $colorInfo;
    }


    private function parseBasicInfo($basicInfo){
        $picture = $basicInfo['picture'];
        $pictureInfo = explode('|',$picture);
        $pictureGroup = ['zhutu'=>[],'color'=>[]];
        foreach($pictureInfo as $key => $val ){
            if(strpos($val,'zhutu') !== false){
                array_push($pictureGroup['zhutu'],$val);
            }else if(strpos($val,'color') !== false){
                array_push($pictureGroup['color'],$val);
            }
        }

        $zhutu = [];
        foreach($pictureGroup['zhutu'] as $val){
            $val = trim($val,";");
            $result = explode(":",$val);
            array_push($zhutu,$result);
        }

        $color = [];
        foreach($pictureGroup['color'] as $val){
            $val = trim($val,";");
            $result = explode(":",$val);
            array_push($color,$result);
        }

        $parsedInfo['zhutu'] = $zhutu;
        $parsedInfo["color"] = $color;

        return $parsedInfo;
    }

    /**
     * 采集一个商品到店铺
     */
    public function spiderItem(){
        set_time_limit(0);

        //调用python获取数据
        //从队列中取出当前要处理的 商品
        $itemId = $this->getItemIdFromQueue();
        //$itemId = '547799203139';

        $basicInfo = $this->getItemBasicInfo($itemId);
        $parsedInfo = $this->parseBasicInfo($basicInfo);

        //上传基本的信息
        $numIId = $this->itemAdd($basicInfo);
        //json_encode之后是这样的 '{"0":"556578063083"}' 不知道是什么原因
        $tmp = json_decode(json_encode($numIId),true);
        $numIId = $tmp[0];
        //$numIId = '556475557855';
        //上传详情描述中的图片    这些图片都在图片空见 通过itemimgupload的上传的最多5张 是在左上角的图片  主图是第一张图 所以主图只有一张
        $descImages = $this->getDescImg($itemId);
        $imageArr = $this->pictureUpload($descImages);
        //更新描述
        $this->itemUpdate($numIId,$imageArr);

        //一直理解错误 主图其实就是第一张  其他的都不是
        //上传主图
        //获取主图
        $mainImages = $this->getMajor($itemId);
        $this->itemImgUpload($numIId,$mainImages);

        //上传属性图片
        //获取属性图片
        $propsImages = $this->getPropsImage($itemId,$parsedInfo['color']);
        //分析基础信息 获取图片信息 区分主图和属性图
        $this->itemPropimgUpload($numIId,$propsImages);
        //完工
        echo "success";
    }




    /**
     * 添加一个商品 先要上传商品的图片 才能在
     * @param $param
     */
    private function itemAdd($basicInfo)
    {
        $param = $basicInfo;

         $req = new ItemAddRequest();
         $req->setNum($param['num']);
         $req->setPrice($param['price']);
         $req->setType("fixed");
         $req->setStuffStatus("new");
         $req->setTitle($param['title']);
         $req->setDesc($param['description']);//详情 初始的description保存采集的商品的地址
         $req->setLocationState($param["location_state"]);
         $req->setLocationCity($param['location_city']);
         $req->setApproveStatus("onsale");
         $req->setCid($param['cid']);
         $req->setProps($param['cateProps']);
         //$req->setWirelessDesc($param["wireless_desc"]);//无线详情
         //$req->setSkuProperties($param['skuProps']);
         $this->resp = $this->topClient->execute($req, $this->loginSession);
         if(isset($this->resp->item->iid)){
             return $this->resp->item->iid;
         }else{
             return false;
         }
    }


    /**
     * 这里的图片上传完毕就行 不用返回 因为上传了 就会自动到左上角 所以后面的返回暂时没有什么用
     * @param $numIId
     * @param $pathArr
     * @param string $major
     * @return array
     */
    private function itemImgUpload($numIId, $pathArr,$major="false"){
        $imageUrlArr = [];
        foreach($pathArr as $key => $val ){
            if($key > 4) continue; //最多5张图
            $req = new ItemImgUploadRequest();
            //$req->setPosition($key+1);
            $req->setNumIid($numIId);
            $req->setImage('@'.$val);
            if($key == 0){
                $major = "true"; //加上这个图才允许5张 除掉这个 只能传四张
            }else{
                $major = "false";
            }
            $req->setIsMajor($major);
            $this->resp = $this->topClient->execute($req, $this->loginSession);
            if(isset($this->resp->item_img->url)){
                array_push($imageUrlArr,$this->resp->item_img->url);
            }
        }
        return $imageUrlArr;
    }

    //描述里的图片都要从这里上传
    private function pictureUpload($pictureArr){
        $urlArr = [];
        foreach($pictureArr as $key => $val ){
            $req = new PictureUploadRequest();
            $req->setPictureCategoryId("0");
            $req->setImg('@'.$val);
            $req->setImageInputTitle(basename($val));
            $resp = $this->topClient->execute($req, $this->loginSession);
            if(isset($resp->picture->picture_path)){
                array_push($urlArr,$resp->picture->picture_path);
            }
        }
        return $urlArr;
    }



    private function itemPropimgUpload($itemIid,$propsImages){
        foreach($propsImages as $key => $val ){
            $req = new ItemPropimgUploadRequest();
            $req->setNumIid($itemIid);
            $req->setProperties($val[3].":".$val[4]);
            $req->setImage('@'.$val['path']);
            $resp = $this->topClient->execute($req, $this->loginSession);
        }

    }

    private function itemUpdate($numIId,$imageArr){
        $req = new ItemUpdateRequest();
        $req->setNumIid($numIId);

        $desc = '';
        foreach($imageArr as $key => $val ){
            $desc .= "<img src='".$val."'>";
        }
        $req->setDesc($desc);
        $this->resp = $this->topClient->execute($req, $this->loginSession);
    }





















    /**
     * 获取属性信息
     */
    private function itemPropsGet(Request $request ){

        $param = $request->only(["cid",'type']);

        if(!isset($param['type'])) $param['type'] = "cid";


        $req = new ItempropsGetRequest;
        $req->setFields("pid,name,must,multi,prop_values");
        //$req->setParentPid(6384766);

        $req->setCid($param['cid']);
        $req->setPid(148886213);

        $this->resp = $this->topClient->execute($req);
        var_export($this->resp);
    }




    /**
     * 也是获取属性的
     */
    private function itemPropValuesGet(){

        $req = new ItempropvaluesGetRequest;
        $req->setFields("cid,pid,prop_name,vid,name");
        $req->setCid("50010850");
        //$req->setPvs("通勤");
        //$req->setType("1");
        $resp = $this->topClient->execute($req);
        var_export($resp);
    }


    /**
     * 采集所有的类目 入库
     */
    private function categorySpider()
    {
        //当然是从0开始
        $recode = Db::table("category")->where("status is null")->where('is_parent',"1")->order("id asc")->limit(1)->find();

        $this->itemCatsGet($recode['cid']);
    }





    private function spiderMenu(){
        $ing = Db::table("complatecats")->where('is_spiding','1')->find();
        if($ing){
            echo '---正在采集上一条 请稍后---';exit;
        }
        $res = Db::table('complatecats')->where('is_spider','0')->order("id asc")->find();

        if($res) {
            $sid = $res['sid'];
        }else{
            //第一次采集
            $sid = 0;
        }
        $this->spider($sid,$res);
    }

    private function spider($sid,$data){
        Db::table('complatecats')->where('sid', $sid)->update(['is_spider' => '1','is_spiding'=>'1']);

        //判断sid的类型
        $parent_pv = '';
        $postParam = ['path'=>'', 'sid'=>'','pv'=>''];
        if(!$sid){
            $postParam['path'] = 'all';
            $parent_sid = 0;
        }else{
            if(strpos($sid,":") !== false){
                $postParam['pv'] = $sid;
                $postParam['path'] = 'next';
                $postParam['sid'] = $data['parent_sid'];
                $parent_sid = $data['parent_sid'];
                $parent_pv = $sid;
            }else{
                $postParam['sid'] = $sid;
                $postParam['path'] = 'next';
                $parent_sid = $sid;
            }
        }

        $url = "https://upload.taobao.com/auction/json/reload_cats.htm?customId=&fenxiaoProduct=";

        $cookie = <<<Cookie
thw=cn; UM_distinctid=15bf5294b72144-05d1ff5c378185-3141775c-1fa400-15bf5294b73352; miid=1248107060361705963; l=AjU140dHkyWSkxPAw6W48nZ1xbvvgOnB; _m_h5_tk=1a6c738d2458899d1d47f6264b739c6d_1497326836307; _m_h5_tk_enc=db5a1b835341a6aa5d170d3961e8008a; v=0; uc3=sg2=AQWdKJxztwwTxFbBImjAc7ZFZ8rdZ46Kb3xBSSl6pJU%3D&nk2=G4mvSiIyoCUivr5NcF0KoA%3D%3D&id2=UNGSCkTibMMa&vt3=F8dBzWCsfT6MfuwE0Z8%3D&lg2=U%2BGCWk%2F75gdr5Q%3D%3D; existShop=MTQ5Nzg1MTQ4Mw%3D%3D; uss=UtAAsLqj%2B5eak%2BXPLqJfXUidGBBqawrYFrY9YFZt1gNLFw%2FfWyDl4rMzRQ%3D%3D; lgc=xinlixue20072007; tracknick=xinlixue20072007; sg=784; mt=np=&ci=6_1&cyk=-1_-1; skt=02f45b6996d05941; _cc_=Vq8l%2BKCLiw%3D%3D; tg=0; _l_g_=Ug%3D%3D; unb=314210378; cookie17=UNGSCkTibMMa; t=9e20ac451db76b54e89380944272c633; cookie2=1c4dea2f897cbaec1612bc268f53ca46; cookie1=UtIE4fRPIyyga00TW9EmCGCr93PYmYf%2BrEPcbMJr0nU%3D; _tb_token_=8FEOAqjq; _nk_=xinlixue20072007; cna=/N9XEbRb/w8CAXQSFkalZRRb; uc1=cookie16=V32FPkk%2FxXMk5UvIbNtImtMfJQ%3D%3D&cookie21=W5iHLLyFfXVRCJf5lG5%2BkA%3D%3D&cookie15=URm48syIIVrSKA%3D%3D&existShop=true&pas=0&cookie14=UoW%2Bv%2Fxn%2Bd1l7Q%3D%3D&tag=8&lng=zh_CN; apushc4690d9afbd8c2e887b783fcc9dd98cd=%7B%22ts%22%3A1497851540919%2C%22heir%22%3A1497851533749%2C%22parentId%22%3A1497843831999%7D; isg=AqKiGORlD7ru8hL6MiVA8kBc5iio76sv9n9-nuw7pZXAv0A51YMvHFp5m9yi
Cookie;
        $header = [
            "x-requested-with:XMLHttpRequest",
            ":authority:upload.taobao.com",
            ":method:POST",
            ":path:/auction/json/reload_cats.htm?customId=&fenxiaoProduct=",
            ":scheme:https",
            "accept:application/json, text/javascript, */*; q=0.01",
            "origin:https://upload.taobao.com",
        ];
        $referer="https://upload.taobao.com/auction/sell.jhtml?spm=a313o.7775905.a1zvx.d48.IJGrWJ&mytmenu=wym";
        $userAgent = "user-agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.2669.400 QQBrowser/9.6.10990.400";

        $curl = new Curl();
        $curl->setOpt(CURLOPT_RETURNTRANSFER, TRUE);
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, FALSE);
        $curl->setOpt(CURLOPT_COOKIE,$cookie);
        $curl->setOpt(CURLOPT_REFERER,$referer);
        $curl->setOpt(CURLOPT_USERAGENT,$userAgent);
        $curl->setOpt(CURLOPT_HEADER,$header);
        $res = $curl->post($url,$postParam);

        //cookie是否已经失效
        if($res->isRedirect()){
            echo '<span style="color:red;">赶紧重新登录</span>';exit;
        }

        $response = mb_convert_encoding($res->response,'UTF-8','GBK');
        $response = json_decode($response,true);
        //var_export($response);

        if($response) {
            $pMenu = $response[0]['data'];
            foreach ($pMenu as $key => $val) {// 根据分类的类目  $val是类目
                foreach ($val['data'] as $k => $v) {
                    //echo $v['spell'].$v['name'].$v['spuid'].$v['leaf'].$v['sid'].$v['status'].'<br />';
                    Db::table("complatecats")->insert(['spell' => $v['spell'], 'name' => $v['name'], 'spuid' => $v['spuid'], 'leaf' => $v['leaf'], 'sid' => $v['sid'], 'status' => $v['status'], 'parent_sid' => $parent_sid,'parent_pv'=>$parent_pv]);
                }
            }

            Db::table('complatecats')->where('sid', $sid)->update(['is_spider' => '1','is_spiding'=>'0']);
        }else{
            echo "没有子类目--";
            Db::table('complatecats')->where('sid', $sid)->update(['no_child_or_failed' => '1','is_spider'=>'1','is_spiding'=>'0']);
        }
        echo "<span style='color:red;'>".$sid.'</span>|';

    }




    private function testRequest(){
        $url = "https://detailskip.taobao.com/service/getData/1/p1/item/detail/sib.htm?itemId=530378518834&sellerId=58056748&modules=dynStock,qrcode,viewer,price,duty,xmpPromotion,delivery,activity,fqg,zjys,couponActivity,soldQuantity,contract,tradeContract&callback=onSibRequestSuccess";


        $header = [
            ":authority:detailskip.taobao.com",
            ":method:GET",
            ":path:/service/getData/1/p1/item/detail/sib.htm?itemId=530378518834&sellerId=58056748&modules=dynStock,qrcode,viewer,price,duty,xmpPromotion,delivery,activity,fqg,zjys,couponActivity,soldQuantity,contract,tradeContract&callback=onSibRequestSuccess",
            ":scheme:https",
            "accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "accept-encoding:gzip, deflate, sdch, br",
            "accept-language:zh-CN,zh;q=0.8",
            "cache-control:no-cache",
        ];
        $referer="https://item.taobao.com/item.htm?spm=5148.7631246.0.0.8onjis&id=530378518834&qq-pf-to=pcqq.c2c";
        $userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.2669.400 QQBrowser/9.6.10990.400";

        $curl = new Curl();
        $curl->setOpt(CURLOPT_RETURNTRANSFER, TRUE);
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, FALSE);
        //$curl->setOpt(CURLOPT_COOKIE,$cookie);
        $curl->setOpt(CURLOPT_REFERER,$referer);
        $curl->setOpt(CURLOPT_USERAGENT,$userAgent);
        $curl->setOpt(CURLOPT_HEADER,$header);
        $res = $curl->get($url);
        echo $res->response;
    }


    /**
     * 获取类目信息
     */
    private function itemCatsGet($parentCid = 0){
        echo $parentCid;
        $req = new ItemcatsGetRequest;
        $req->setCids($parentCid);
        //$req->setDatetime("2000-01-01 00:00:00");
        $req->setFields("cid,parent_cid,name,is_parent");
        $parentCid = $parentCid.'';//字符串类型的参数才有效果
        //$req->setParentCid($parentCid);
        $resp = $this->topClient->execute($req);
        var_dump($resp);
        if(isset($resp->code)){
            echo "<br />不能在调用了".$parentCid."<br />";
            return;//遇到错误即不能继续调用了 立即停止 然后等待可以继续调用 从断点重新开始
        }
        exit;
        $subCategory = $resp->xpath("item_cats/item_cat");
        foreach($subCategory as $key => $val ){
            if($val->is_parent == "true"){
                $is_parent = "1";
            }else{
                $is_parent = "0";
            }
            $data = ["cid"=>$val->cid,"is_parent"=>$is_parent,"parent_cid"=>$val->parent_cid,"name"=>$val->name];

            //看看是不是已经有了
            $exists = Db::table("category")->where('cid',$val->cid)->find();
            if( $exists ){
                echo "已经采集过了--";
            }else {
                Db::table("category")->insert($data);
            }
        }

        Db::table("category")->where("cid",$parentCid)->update(['status'=>"1"]);

        echo $parentCid;
    }
}